﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkETL
{
    public interface IExecuteBatchedCommand
    {
        IEnumerable<int> Execute(DbContext dbContext, BatchedCommand batchedCommand);
    }

    public class ExecuteBatchedCommand : IExecuteBatchedCommand
    {
        public IEnumerable<int> Execute(DbContext dbContext, BatchedCommand batchedCommand)
        {
            List<int> ids = new List<int>();
            var connectionString = dbContext.Database.Connection.ConnectionString;

            using (SqlConnection sqlConn = new SqlConnection(connectionString))
            {
                using (SqlCommand command = sqlConn.CreateCommand())
                {
                    command.CommandText = batchedCommand.Sql;
                    command.Parameters.AddRange(batchedCommand.Parameters);
                    sqlConn.Open();
                    SqlDataReader reader = command.ExecuteReader();

                    while (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            ids.Add(reader.GetInt32(0));
                        }
                        reader.NextResult();
                    }
                }
                sqlConn.Close();
            }

            return ids;
        }
    }
}
